package com.ymj.service.impl;

import cn.hutool.core.io.FileUtil;
import com.ymj.config.YmjProperties;
import com.ymj.service.PhotoService;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class PhotoServiceImpl implements PhotoService {
    
    @Autowired
    private YmjProperties properties;
    
    static {
        // 加载OpenCV库
        nu.pattern.OpenCV.loadShared();
        System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
    }
    
    @Override
    public Map<String, Object> getPhotoSizes() {
        return new HashMap<>(properties.getPhotoSizes());
    }
    
    @Override
    public String processIdPhoto(MultipartFile file, String size, String background, String[] options) {
        try {
            // 1. 保存上传的文件
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;
            Path uploadPath = Paths.get(properties.getUploadPath());
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            Path filePath = uploadPath.resolve(filename);
            Files.copy(file.getInputStream(), filePath);
            
            // 2. 读取图片
            Mat image = Imgcodecs.imread(filePath.toString());
            if (image.empty()) {
                throw new RuntimeException("无法读取图片");
            }
            
            // 3. 调整大小
            YmjProperties.PhotoSize photoSize = properties.getPhotoSizes().get(size);
            if (photoSize == null) {
                throw new RuntimeException("不支持的证件照尺寸");
            }
            
            Mat resized = new Mat();
            Size targetSize = new Size(photoSize.getWidth(), photoSize.getHeight());
            Imgproc.resize(image, resized, targetSize);
            
            // 4. 应用美化选项
            if (options != null) {
                for (String option : options) {
                    switch (option) {
                        case "whitening":
                            // 美白
                            Core.add(resized, new Scalar(30, 30, 30), resized);
                            break;
                        case "removeWrinkle":
                            // 去皱
                            Imgproc.GaussianBlur(resized, resized, new Size(3, 3), 0);
                            break;
                        case "removeAcne":
                            // 去痘
                            Imgproc.medianBlur(resized, resized, 3);
                            break;
                        case "faceLift":
                            // 瘦脸
                            // 这里需要更复杂的图像处理算法
                            break;
                    }
                }
            }
            
            // 5. 创建背景
            BufferedImage backgroundImage = new BufferedImage(
                photoSize.getWidth(),
                photoSize.getHeight(),
                BufferedImage.TYPE_INT_RGB
            );
            Graphics2D g2d = backgroundImage.createGraphics();
            
            // 设置背景颜色
            switch (background) {
                case "blue":
                    g2d.setColor(new Color(67, 142, 219));
                    break;
                case "red":
                    g2d.setColor(new Color(190, 42, 65));
                    break;
                default:
                    g2d.setColor(Color.WHITE);
            }
            g2d.fillRect(0, 0, photoSize.getWidth(), photoSize.getHeight());
            g2d.dispose();
            
            // 6. 合成图片
            String processedFilename = "processed_" + filename;
            Path processedPath = Paths.get(properties.getTempPath(), processedFilename);
            if (!Files.exists(processedPath.getParent())) {
                Files.createDirectories(processedPath.getParent());
            }
            
            // 保存处理后的图片
            ImageIO.write(backgroundImage, "jpg", processedPath.toFile());
            Mat background = Imgcodecs.imread(processedPath.toString());
            
            // 合成
            Mat mask = new Mat();
            Imgproc.cvtColor(resized, mask, Imgproc.COLOR_BGR2GRAY);
            Core.bitwise_not(mask, mask);
            
            Mat result = new Mat();
            Core.add(background, resized, result, mask);
            
            // 保存结果
            Imgcodecs.imwrite(processedPath.toString(), result);
            
            // 清理临时文件
            Files.deleteIfExists(filePath);
            
            return processedPath.toString();
            
        } catch (IOException e) {
            log.error("处理证件照失败", e);
            throw new RuntimeException("处理证件照失败: " + e.getMessage());
        }
    }
    
    @Override
    public String exportPrintFile(String processedUrl, int rows, int cols, String size, int spacing) {
        try {
            // 1. 读取处理后的图片
            File processedFile = new File(processedUrl);
            BufferedImage source = ImageIO.read(processedFile);
            
            // 2. 获取照片尺寸
            YmjProperties.PhotoSize photoSize = properties.getPhotoSizes().get(size);
            if (photoSize == null) {
                throw new RuntimeException("不支持的证件照尺寸");
            }
            
            // 3. 计算打印布局尺寸
            int printWidth = photoSize.getWidth() * cols + spacing * (cols - 1);
            int printHeight = photoSize.getHeight() * rows + spacing * (rows - 1);
            
            // 4. 创建打印布局
            BufferedImage printLayout = new BufferedImage(
                printWidth,
                printHeight,
                BufferedImage.TYPE_INT_RGB
            );
            Graphics2D g2d = printLayout.createGraphics();
            
            // 设置白色背景
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, printWidth, printHeight);
            
            // 5. 复制照片到布局
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    int x = j * (photoSize.getWidth() + spacing);
                    int y = i * (photoSize.getHeight() + spacing);
                    g2d.drawImage(source, x, y, null);
                }
            }
            g2d.dispose();
            
            // 6. 保存打印文件
            String printFilename = "print_" + UUID.randomUUID().toString() + ".jpg";
            Path printPath = Paths.get(properties.getTempPath(), printFilename);
            ImageIO.write(printLayout, "jpg", printPath.toFile());
            
            return printPath.toString();
            
        } catch (IOException e) {
            log.error("导出打印文件失败", e);
            throw new RuntimeException("导出打印文件失败: " + e.getMessage());
        }
    }
} 